<template>
  <div class="container mx-auto px-4 py-6">
    <!-- Back button and title -->
    <div class="flex items-center space-x-4 mb-6">
      <button 
        class="p-2 text-gray-500 hover:text-primary transition-custom"
        @click="$router.push('/plants')"
      >
        <i class="fa fa-arrow-left text-xl"></i>
      </button>
      <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">{{ plant.name }}</h2>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- Main Info Card -->
      <div class="lg:col-span-1">
        <div class="bg-white rounded-xl shadow-custom">
          <div class="aspect-w-16 aspect-h-9">
            <img
              :src="plant.image || 'https://picsum.photos/800/450'"
              :alt="plant.name"
              class="w-full h-[300px] object-cover rounded-t-xl"
            />
          </div>
          <div class="p-6 space-y-4">
            <div class="space-y-2">
              <div class="flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-800">基本信息</h3>
                <button
                  class="text-primary hover:text-primary/80"
                  @click="$router.push(`/plants/${$route.params.id}/edit`)"
                >
                  <i class="fa fa-edit"></i>
                </button>
              </div>
              <div class="space-y-2 text-gray-600">
                <p><span class="font-medium">学名：</span>{{ plant.scientificName }}</p>
                <p><span class="font-medium">类别：</span>{{ plant.category }}</p>
                <p><span class="font-medium">分布地区：</span>{{ plant.region }}</p>
                <p><span class="font-medium">添加时间：</span>{{ plant.createdAt }}</p>
                <p><span class="font-medium">更新时间：</span>{{ plant.updateTime }}</p>
              </div>
            </div>
            <div class="space-y-2">
              <h3 class="text-lg font-semibold text-gray-800">描述</h3>
              <p class="text-gray-600 whitespace-pre-line">{{ plant.description }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- Components Section -->
      <div class="lg:col-span-1">
        <div class="bg-white rounded-xl shadow-custom p-6">
          <div class="flex items-center justify-between mb-6">
            <h3 class="text-lg font-semibold text-gray-800">主要成分</h3>
            <div class="flex items-center space-x-2">
              <el-input
                v-model="componentSearch"
                placeholder="搜索成分..."
                prefix-icon="el-icon-search"
                size="small"
                class="w-40"
              />
              <el-button 
                type="primary" 
                size="small"
                @click="showAddComponentDialog"
              >
                <i class="fa fa-plus mr-1"></i>
                添加
              </el-button>
            </div>
          </div>
          
          <div class="space-y-4">
            <div
              v-for="component in filteredComponents"
              :key="component.id"
              class="p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-custom group"
            >
              <div class="flex items-center justify-between">
                <div>
                  <h4 class="font-medium text-gray-800">{{ component.name }}</h4>
                  <p class="mt-1 text-sm text-gray-500">分子式：{{ component.formula }}</p>
                  <p class="text-sm text-gray-500">含量：{{ component.content }}%</p>
                </div>
                <div class="opacity-0 group-hover:opacity-100 transition-custom">
                  <el-button-group>
                    <el-button 
                      type="text" 
                      size="mini"
                      @click="editComponent(component)"
                    >
                      <i class="fa fa-edit text-primary"></i>
                    </el-button>
                    <el-button 
                      type="text" 
                      size="mini"
                      @click="deleteComponent(component)"
                    >
                      <i class="fa fa-trash text-danger"></i>
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </div>
          </div>

          <!-- Empty state -->
          <div v-if="!plant.components?.length" class="text-center py-8">
            <i class="fa fa-flask text-4xl text-gray-300"></i>
            <p class="mt-2 text-gray-500">暂无成分信息</p>
          </div>
        </div>
      </div>

      <!-- Achievements Section -->
      <div class="lg:col-span-1">
        <div class="bg-white rounded-xl shadow-custom p-6">
          <div class="flex items-center justify-between mb-6">
            <h3 class="text-lg font-semibold text-gray-800">研究成果</h3>
            <div class="flex items-center space-x-2">
              <el-select 
                v-model="achievementFilter" 
                placeholder="筛选类型"
                size="small"
                class="w-32"
              >
                <el-option label="全部" value="" />
                <el-option label="论文" value="paper" />
                <el-option label="专利" value="patent" />
                <el-option label="项目" value="project" />
              </el-select>
              <el-button 
                type="primary" 
                size="small"
                @click="showAddAchievementDialog"
              >
                <i class="fa fa-plus mr-1"></i>
                添加
              </el-button>
            </div>
          </div>

          <div class="space-y-4">
            <div
              v-for="achievement in filteredAchievements"
              :key="achievement.id"
              class="p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-custom group cursor-pointer"
              @click="viewAchievement(achievement)"
            >
              <div class="flex items-center justify-between">
                <div class="flex-1">
                  <div class="flex items-center space-x-2">
                    <span 
                      :class="getAchievementTypeClass(achievement.type)"
                      class="px-2 py-0.5 text-xs rounded-full"
                    >
                      {{ getAchievementTypeText(achievement.type) }}
                    </span>
                    <h4 class="font-medium text-gray-800">{{ achievement.title }}</h4>
                  </div>
                  <p class="mt-2 text-sm text-gray-600 line-clamp-2">{{ achievement.content }}</p>
                  <div class="mt-2 flex items-center text-xs text-gray-500">
                    <i class="fa fa-calendar-alt mr-1"></i>
                    <span>{{ achievement.date }}</span>
                  </div>
                </div>
                <div class="opacity-0 group-hover:opacity-100 transition-custom ml-4">
                  <el-button-group>
                    <el-button 
                      type="text" 
                      size="mini"
                      @click.stop="editAchievement(achievement)"
                    >
                      <i class="fa fa-edit text-primary"></i>
                    </el-button>
                    <el-button 
                      type="text" 
                      size="mini"
                      @click.stop="deleteAchievement(achievement)"
                    >
                      <i class="fa fa-trash text-danger"></i>
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </div>
          </div>

          <!-- Empty state -->
          <div v-if="!plant.achievements?.length" class="text-center py-8">
            <i class="fa fa-award text-4xl text-gray-300"></i>
            <p class="mt-2 text-gray-500">暂无研究成果</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Component Dialog -->
    <el-dialog
      :title="componentForm.id ? '编辑成分' : '添加成分'"
      :visible.sync="componentDialogVisible"
      width="500px"
    >
      <el-form 
        ref="componentForm"
        :model="componentForm"
        :rules="componentRules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="componentForm.name" />
        </el-form-item>
        <el-form-item label="分子式" prop="formula">
          <el-input v-model="componentForm.formula" />
        </el-form-item>
        <el-form-item label="含量" prop="content">
          <el-input v-model="componentForm.content">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="componentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitComponent" :loading="submitting">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- Achievement Dialog -->
    <el-dialog
      :title="achievementForm.id ? '编辑成果' : '添加成果'"
      :visible.sync="achievementDialogVisible"
      width="500px"
    >
      <el-form 
        ref="achievementForm"
        :model="achievementForm"
        :rules="achievementRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="achievementForm.title" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="achievementForm.type" placeholder="请选择类型" class="w-full">
            <el-option label="论文" value="paper" />
            <el-option label="专利" value="patent" />
            <el-option label="项目" value="project" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="achievementForm.content"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="achievementForm.date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            class="w-full"
          />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="achievementDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAchievement" :loading="submitting">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'PlantDetailView',
  data() {
    return {
      plant: {
        name: '',
        scientificName: '',
        category: '',
        region: '',
        description: '',
        image: null,
        createdAt: '',
        updateTime: '',
        components: [],
        achievements: []
      },
      componentSearch: '',
      achievementFilter: '',
      componentDialogVisible: false,
      achievementDialogVisible: false,
      submitting: false,
      componentForm: {
        id: null,
        name: '',
        formula: '',
        content: ''
      },
      componentRules: {
        name: [{ required: true, message: '请输入成分名称', trigger: 'blur' }],
        formula: [{ required: true, message: '请输入分子式', trigger: 'blur' }],
        content: [
          { required: true, message: '请输入含量', trigger: 'blur' },
          { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: 'blur' }
        ]
      },
      achievementForm: {
        id: null,
        title: '',
        type: '',
        content: '',
        date: ''
      },
      achievementRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        date: [{ required: true, message: '请选择日期', trigger: 'change' }]
      }
    }
  },
  computed: {
    filteredComponents() {
      if (!this.componentSearch) return this.plant.components
      const search = this.componentSearch.toLowerCase()
      return this.plant.components.filter(component => 
        component.name.toLowerCase().includes(search) ||
        component.formula.toLowerCase().includes(search)
      )
    },
    filteredAchievements() {
      let result = this.plant.achievements
      if (this.achievementFilter) {
        result = result.filter(achievement => achievement.type === this.achievementFilter)
      }
      return result
    }
  },
  async created() {
    await this.fetchPlantData()
  },
  methods: {
    ...mapActions('plants', ['fetchPlantById']),
    
    async fetchPlantData() {
      try {
        // 模拟数据，实际项目中应该调用 API
        this.plant = {
          id: this.$route.params.id,
          name: '银杏',
          scientificName: 'Ginkgo biloba',
          category: '乔木',
          region: '华东',
          description: '银杏是世界上现存最古老的裸子植物之一，有"活化石"之称。其叶片扇形，深秋时呈金黄色，具有极高的观赏和药用价值。\n\n银杏具有改善记忆力、增进血液循环等功效，其叶片和果实都可入药。',
          image: 'https://picsum.photos/800/450?random=1',
          createdAt: '2024-01-15',
          updateTime: '2024-03-15',
          components: [
            {
              id: 1,
              name: '银杏内酯A',
              formula: 'C20H24O9',
              content: '0.3'
            },
            {
              id: 2,
              name: '银杏内酯B',
              formula: 'C20H24O10',
              content: '0.2'
            },
            {
              id: 3,
              name: '银杏黄酮',
              formula: 'C15H10O6',
              content: '0.5'
            }
          ],
          achievements: [
            {
              id: 1,
              title: '银杏叶提取物的制备方法及其应用',
              type: 'patent',
              content: '本发明提供了一种从银杏叶中提取银杏内酯的新方法，具有提取效率高、成本低的特点。',
              date: '2024-01-15'
            },
            {
              id: 2,
              title: '银杏内酯对阿尔茨海默病的治疗作用研究',
              type: 'paper',
              content: '研究表明，银杏内酯能显著改善阿尔茨海默病患者的认知功能。',
              date: '2024-02-20'
            },
            {
              id: 3,
              title: '银杏活性成分开发项目',
              type: 'project',
              content: '针对银杏中的活性成分进行深入研究，开发新型药物。',
              date: '2024-03-01'
            }
          ]
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      }
    },

    getAchievementTypeClass(type) {
      const classes = {
        paper: 'bg-blue-100 text-blue-800',
        patent: 'bg-green-100 text-green-800',
        project: 'bg-yellow-100 text-yellow-800'
      }
      return classes[type] || 'bg-gray-100 text-gray-800'
    },

    getAchievementTypeText(type) {
      const texts = {
        paper: '论文',
        patent: '专利',
        project: '项目'
      }
      return texts[type] || type
    },

    showAddComponentDialog() {
      this.componentForm = {
        id: null,
        name: '',
        formula: '',
        content: ''
      }
      this.componentDialogVisible = true
    },

    editComponent(component) {
      this.componentForm = { ...component }
      this.componentDialogVisible = true
    },

    async submitComponent() {
      try {
        await this.$refs.componentForm.validate()
        this.submitting = true
        
        // 模拟 API 调用
        await new Promise(resolve => setTimeout(resolve, 500))
        
        if (this.componentForm.id) {
          const index = this.plant.components.findIndex(c => c.id === this.componentForm.id)
          if (index !== -1) {
            this.plant.components.splice(index, 1, { ...this.componentForm })
          }
        } else {
          this.plant.components.push({
            ...this.componentForm,
            id: Date.now()
          })
        }
        
        this.$message.success('保存成功')
        this.componentDialogVisible = false
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      } finally {
        this.submitting = false
      }
    },

    async deleteComponent(component) {
      try {
        await this.$confirm('确定要删除该成分吗？', '提示', {
          type: 'warning'
        })
        
        // 模拟 API 调用
        await new Promise(resolve => setTimeout(resolve, 500))
        
        this.plant.components = this.plant.components.filter(c => c.id !== component.id)
        this.$message.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    showAddAchievementDialog() {
      this.achievementForm = {
        id: null,
        title: '',
        type: '',
        content: '',
        date: ''
      }
      this.achievementDialogVisible = true
    },

    editAchievement(achievement) {
      this.achievementForm = { ...achievement }
      this.achievementDialogVisible = true
    },

    async submitAchievement() {
      try {
        await this.$refs.achievementForm.validate()
        this.submitting = true
        
        // 模拟 API 调用
        await new Promise(resolve => setTimeout(resolve, 500))
        
        if (this.achievementForm.id) {
          const index = this.plant.achievements.findIndex(a => a.id === this.achievementForm.id)
          if (index !== -1) {
            this.plant.achievements.splice(index, 1, { ...this.achievementForm })
          }
        } else {
          this.plant.achievements.push({
            ...this.achievementForm,
            id: Date.now()
          })
        }
        
        this.$message.success('保存成功')
        this.achievementDialogVisible = false
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      } finally {
        this.submitting = false
      }
    },

    async deleteAchievement(achievement) {
      try {
        await this.$confirm('确定要删除该成果吗？', '提示', {
          type: 'warning'
        })
        
        // 模拟 API 调用
        await new Promise(resolve => setTimeout(resolve, 500))
        
        this.plant.achievements = this.plant.achievements.filter(a => a.id !== achievement.id)
        this.$message.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    viewAchievement(achievement) {
      this.$router.push(`/achievements/${achievement.id}`)
    }
  }
}
</script>

<style scoped>
.transition-custom {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.shadow-custom {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style> 